<template>
  <div class="interview-management-container">
    <div class="page-header">
      <h1 class="page-title">面试管理</h1>
      <p class="page-subtitle">管理您创建的所有面试</p>
      <div class="header-actions">
        <el-button @click="loadInterviews" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="createInterview">
          <el-icon><Plus /></el-icon>
          创建新面试
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><DataBoard /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalInterviews }}</div>
          <div class="stat-label">总面试数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon active">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ activeInterviews }}</div>
          <div class="stat-label">进行中</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon completed">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ completedInterviews }}</div>
          <div class="stat-label">已完成</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon pending">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ pendingInterviews }}</div>
          <div class="stat-label">待开始</div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filters-section">
      <div class="filter-row">
        <div class="filter-item">
          <el-input 
            v-model="searchQuery" 
            placeholder="搜索面试名称或岗位"
            prefix-icon="Search"
            clearable
          />
        </div>
        
        <div class="filter-item">
          <el-select v-model="statusFilter" placeholder="选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待开始" value="pending" />
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </div>
        
        <div class="filter-item">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-section">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 面试列表 -->
    <div v-else class="interviews-list">
      <div 
        v-for="interview in filteredInterviews" 
        :key="interview.id"
        class="interview-card"
        @click="viewInterviewDetail(interview.id)"
      >
        <div class="card-header">
          <div class="interview-title">
            <h3>{{ interview.title }}</h3>
            <el-tag 
              :type="getStatusType(interview.status)"
              class="status-tag"
            >
              {{ getStatusText(interview.status) }}
            </el-tag>
          </div>
          <div class="card-actions">
            <el-dropdown @command="handleCommand">
              <el-button type="text">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'edit', id: interview.id}">
                    <el-icon><Edit /></el-icon>
                    编辑面试
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'duplicate', id: interview.id}">
                    <el-icon><CopyDocument /></el-icon>
                    复制面试
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'statistics', id: interview.id}">
                    <el-icon><DataAnalysis /></el-icon>
                    查看统计
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', id: interview.id}" divided>
                    <el-icon><Delete /></el-icon>
                    删除面试
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="card-content">
          <div class="interview-meta">
            <div class="meta-item">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ interview.position }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(interview.createdAt) }}</span>
            </div>
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>{{ interview.candidateCount }}名候选人</span>
            </div>
          </div>
          
          <div class="interview-progress">
            <div class="progress-info">
              <span class="progress-label">面试进度</span>
              <span class="progress-text">{{ interview.completedCount }}/{{ interview.candidateCount }}</span>
            </div>
            <el-progress 
              :percentage="getProgressPercentage(interview)" 
              :color="getProgressColor(interview)"
              :stroke-width="8"
            />
          </div>
          
          <div class="interview-description">
            <p>{{ interview.description }}</p>
          </div>
        </div>
        
        <div class="card-footer">
          <div class="candidate-avatars">
            <div class="avatars-group">
              <el-avatar 
                v-for="candidate in interview.recentCandidates" 
                :key="candidate.id"
                :src="candidate.avatar"
                :size="32"
                class="candidate-avatar"
              >
                {{ candidate.name.charAt(0) }}
              </el-avatar>
              <div 
                v-if="interview.candidateCount > 4" 
                class="more-candidates"
              >
                +{{ interview.candidateCount - 4 }}
              </div>
            </div>
          </div>
          
          <div class="action-buttons">
            <el-button 
              type="primary" 
              size="small"
              @click.stop="viewInterviewDetail(interview.id)"
            >
              查看详情
            </el-button>
            <el-button 
              size="small"
              @click.stop="viewStatistics(interview.id)"
            >
              查看统计
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredInterviews.length === 0" class="empty-state">
      <el-empty description="暂无面试数据">
        <el-button type="primary" @click="createInterview">创建第一个面试</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onActivated, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { businessApi as api } from '@/services/api';
import { 
  DataBoard, 
  User, 
  CircleCheck, 
  Clock, 
  OfficeBuilding, 
  Calendar,
  MoreFilled,
  Edit,
  CopyDocument,
  DataAnalysis,
  Delete
} from '@element-plus/icons-vue'

export default {
  name: 'InterviewManagementView',
  components: {
    Plus,
    DataBoard,
    User,
    CircleCheck,
    Clock,
    OfficeBuilding,
    Calendar,
    MoreFilled,
    Edit,
    CopyDocument,
    DataAnalysis,
    Delete
  },
  setup() {
    const router = useRouter()
    
    // 筛选条件
    const searchQuery = ref('')
    const statusFilter = ref('')
    const dateRange = ref('')
    
    // 面试数据
    const interviews = ref([])
    const loading = ref(false)
    
    // 计算属性
    const totalInterviews = computed(() => interviews.value.length)
    const activeInterviews = computed(() => interviews.value.filter(i => i.status === 'active').length)
    const completedInterviews = computed(() => interviews.value.filter(i => i.status === 'completed').length)
    const pendingInterviews = computed(() => interviews.value.filter(i => i.status === 'pending').length)
    
    const filteredInterviews = computed(() => {
      let filtered = interviews.value.slice()
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(interview => 
          interview.title.toLowerCase().includes(query) ||
          interview.position.toLowerCase().includes(query)
        )
      }
      
      // 状态过滤
      if (statusFilter.value) {
        filtered = filtered.filter(interview => interview.status === statusFilter.value)
      }
      
      // 日期范围过滤
      if (dateRange.value && dateRange.value.length === 2) {
        const [startDate, endDate] = dateRange.value
        filtered = filtered.filter(interview => {
          const createdDate = new Date(interview.createdAt)
          return createdDate >= new Date(startDate) && createdDate <= new Date(endDate)
        })
      }
      
      return filtered
    })
    
    // 方法
    const createInterview = () => {
      router.push('/hr/create-interview')
    }
    
    const viewInterviewDetail = (interviewId) => {
      // 由于我们现在使用的是job.id，导航到申请管理页面更合适
      // 如果interviewId是以job_开头的字符串，去掉前缀
      const jobId = typeof interviewId === 'string' && interviewId.startsWith('job_') 
        ? interviewId.replace('job_', '') 
        : interviewId
      
      router.push(`/hr/applications?job=${jobId}`)
    }
    
    const viewStatistics = (interviewId) => {
      router.push(`/hr/statistics?job=${interviewId}`)
    }
    
    const handleCommand = (command) => {
      const { action, id } = command
      
      switch (action) {
        case 'edit':
          // 由于现在使用的是job.id，导航到编辑职位页面
          router.push(`/hr/create-interview/${id}`)
          break
        case 'duplicate':
          console.log('复制面试:', id)
          break
        case 'statistics':
          viewStatistics(id)
          break
        case 'delete':
          console.log('删除面试:', id)
          break
      }
    }
    
    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleDateString('zh-CN')
    }
    
    const getStatusType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'active': 'success',
        'completed': 'info'
      }
      return typeMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待开始',
        'active': '进行中',
        'completed': '已完成'
      }
      return textMap[status] || '未知'
    }
    
    const getProgressPercentage = (interview) => {
      if (interview.candidateCount === 0) return 0
      return Math.round((interview.completedCount / interview.candidateCount) * 100)
    }
    
    const getProgressColor = (interview) => {
      const percentage = getProgressPercentage(interview)
      if (percentage === 100) return '#67c23a'
      if (percentage >= 50) return '#e6a23c'
      return '#f56c6c'
    }
    
    // 加载面试数据
    const loadInterviews = async () => {
      loading.value = true
      try {
        // 1. 获取所有职位申请数据，而不是职位发布数据
        const applicationsResponse = await api.getJobApplications()
        const applicationsData = applicationsResponse.data || applicationsResponse
        
        // 处理分页数据格式，提取results数组
        let applications = []
        if (Array.isArray(applicationsData)) {
          applications = applicationsData
        } else if (applicationsData && applicationsData.results && Array.isArray(applicationsData.results)) {
          applications = applicationsData.results
        } else {
          console.error('无法解析申请数据:', applicationsData)
          ElMessage.error('申请数据格式错误')
          interviews.value = []
          return
        }
        
        // 如果没有申请数据，直接返回空数组
        if (applications.length === 0) {
          interviews.value = []
          ElMessage.info('暂无申请数据，请先发布职位')
          return
        }
        
        // 添加调试日志
        console.log('获取到的申请数据:', applicationsData)
        
        // 调试：打印第一个申请的字段
        if (applications.length > 0) {
          console.log('第一个申请数据的字段:', Object.keys(applications[0]))
          console.log('第一个申请数据:', applications[0])
        }
        
        // 2. 按职位分组申请数据，创建面试管理数据
        const jobGroups = {}
        applications.forEach(app => {
          // 尝试多种可能的字段名来获取job_id
          let jobKey = app.job_posting || app.job_id || app.job?.id || app.jobId || app.job_posting_id || app.job_posting?.id
          
          // 如果仍然找不到job_id，使用申请的job_title作为分组键
          if (!jobKey) {
            jobKey = `job_${app.job_title || app.job?.title || 'unknown'}`
          }
          
          console.log(`申请 ${app.id} 的job信息:`, {
            job_posting: app.job_posting,
            job_id: app.job_id,
            job: app.job,
            jobId: app.jobId,
            job_posting_id: app.job_posting_id,
            job_posting_obj: app.job_posting,
            final_jobKey: jobKey
          })
          
          if (!jobGroups[jobKey]) {
            jobGroups[jobKey] = {
              jobId: jobKey,
              title: app.job?.title || app.job_title || app.job_posting?.title || '未知职位',
              position: app.job?.title || app.job_title || app.job_posting?.title || '未知职位',
              description: app.job?.description || app.job_posting?.description || '',
              applications: [],
              createdAt: app.applied_at || app.created_at
            }
          }
          jobGroups[jobKey].applications.push(app)
        })
        
        console.log('分组后的job数据:', jobGroups)
        
        // 3. 转换为面试管理数据格式
        const interviewsData = Object.values(jobGroups).map(group => {
          const totalCount = group.applications.length
          const completedCount = group.applications.filter(app => 
            app.status === 'completed' || app.status === 'hired' || app.status === 'rejected'
          ).length
          
          // 确定面试状态
          let status = 'pending'
          if (completedCount === totalCount && totalCount > 0) {
            status = 'completed'
          } else if (completedCount > 0) {
            status = 'active'
          }
          
          return {
            id: group.jobId,
            title: `${group.title} - 面试`,
            position: group.position,
            status: status,
            createdAt: group.createdAt,
            candidateCount: totalCount,
            completedCount: completedCount,
            description: group.description || `${group.title}的面试流程`,
            recentCandidates: group.applications.slice(0, 4).map(app => ({
              id: app.id,
              name: app.candidate_name || app.name || '未知候选人',
              avatar: app.candidate_avatar || ''
            }))
          }
        })
        
        interviews.value = interviewsData
        
        if (interviews.value.length === 0) {
          ElMessage.info('暂无面试数据，您可以创建第一个面试')
        }
        
      } catch (error) {
        console.error('加载面试数据失败:', error)
        ElMessage.error('加载面试数据失败，请检查网络连接')
        
        // 使用演示数据作为备用
        interviews.value = [
          {
            id: 1,
            title: '前端开发工程师面试',
            position: '前端开发工程师',
            status: 'active',
            createdAt: '2024-01-10',
            candidateCount: 15,
            completedCount: 8,
            description: '针对前端开发岗位的综合面试，包含技术能力、逻辑思维、沟通表达等多个维度的评估',
            recentCandidates: [
              { id: 1, name: '张三', avatar: '' },
              { id: 2, name: '李四', avatar: '' },
              { id: 3, name: '王五', avatar: '' },
              { id: 4, name: '赵六', avatar: '' }
            ]
          }
        ]
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
  loadInterviews()
})

// 每次页面激活时重新加载数据（解决从创建页面返回时数据不更新的问题）
onActivated(() => {
  loadInterviews()
})
    
    return {
      searchQuery,
      statusFilter,
      dateRange,
      loading,
      totalInterviews,
      activeInterviews,
      completedInterviews,
      pendingInterviews,
      filteredInterviews,
      createInterview,
      viewInterviewDetail,
      viewStatistics,
      handleCommand,
      formatDate,
      getStatusType,
      getStatusText,
      getProgressPercentage,
      getProgressColor,
      loadInterviews
    }
  }
}
</script>

<style scoped>
.interview-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
}

.page-title {
  font-size: 2rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 1rem;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  background: var(--primary-color);
}

.stat-icon.active {
  background: #67c23a;
}

.stat-icon.completed {
  background: #409eff;
}

.stat-icon.pending {
  background: #e6a23c;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 2rem;
  font-weight: 600;
  color: var(--text-primary);
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.filters-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  min-width: 200px;
}

.interviews-list {
  display: grid;
  gap: 20px;
}

.interview-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.interview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.interview-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.interview-title h3 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-primary);
}

.status-tag {
  font-size: 12px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.card-content {
  margin-bottom: 16px;
}

.interview-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--text-secondary);
  font-size: 14px;
}

.interview-progress {
  margin-bottom: 16px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.progress-label {
  font-size: 14px;
  color: var(--text-secondary);
}

.progress-text {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
}

.interview-description {
  color: var(--text-secondary);
  font-size: 14px;
  line-height: 1.5;
}

.interview-description p {
  margin: 0;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.candidate-avatars {
  display: flex;
  align-items: center;
}

.avatars-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.candidate-avatar {
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.more-candidates {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: var(--text-secondary);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading-section {
  padding: 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    min-width: auto;
  }
  
  .interview-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .card-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style> 